/**
 * protobuf 相关的操作类,用来获得可被实例化的类列表，一般使用：
 * import * as protobuf from './lib/protobuf/protobuf-msg';
 * let class = protobuf.getMsgProto();
 * let login_login_c2s = new class.login_login_c2s();
 * login_login_c2s.setUserName("test");
 * console.log(login_login_c2s);|client.send(login_login_c2s.toArrayBuffer());
 * @module lib/protobuf/protobof-msg
 */
import * as protobufjs from 'protobufjs';
import * as fs from 'fs';
import * as path from 'path';
import * as log from '../log/log';
import * as serverConfig from '../config/config';

/**
 * 私有方法，请调用getMsgProto()获得类列表
 */
export let _msgBuilder : protoBufMsg.ProtoBufBuilder;
export function getMsgProto(){
    if(_msgBuilder==null){
        let _path = serverConfig.getRootPath()+path.normalize("asset/server/proto/msg.proto");
        _msgBuilder =  loadProtoFileSync(_path,'protoBufMsg');
    }
    return _msgBuilder;
}


/**
 * 加载特定的protobuf协议文件，并且需要定义命名空间
 * 
 * @export
 * @param {string} _path    路径
 * @param {string} _package 包名
 * @returns 返回消息类列表
 */
export function loadProtoFileSync(_path:string,_package:string){

    if(fs.existsSync(_path)){
        let str = fs.readFileSync(_path,'utf-8');
        let proto = protobufjs.loadProto(str,null,_path);
        return proto.build(_package) as any;
    }else{
        log.error('protobuf-msg.loadProtoFileSync file not exists :',_path);
    }
    return null;
}
